package main

import (
	"flag"
	"fmt"
	"gitee.com/larry_dev/goban"
	"gitee.com/larry_dev/gtpengine"
	"gitee.com/larry_dev/gtpengine/gtpcommand"
	"runtime"
	"strings"
)

var (
	move   int
	shell  string
	game   int
	afters string
	sgf string
)

func init() {
	flag.StringVar(&shell, "shell", "./normal.sh", "脚本")
	flag.IntVar(&move, "move", 300, "落子手数")
	flag.IntVar(&game, "game", 1, "对弈数")
	flag.StringVar(&afters, "afters", "", "执行命令")
	flag.StringVar(&sgf,"sgf","","落子")
	flag.Parse()
}
func main() {
	if sgf!=""{
		client, err := gtpcommand.NewCMDClientString(shell)
		if err != nil {
			panic(err)
		}
		gtp := gtpengine.NewGTPCommand(client)
		kifu:=goban.ParseSgf(sgf)
		kifu.EachNode(func(n *goban.Node, move int) bool {
			for _,v:=range n.Steup{
				gtp.Move(v.GetColor(),goban.CoorToBoardNode(v.X,v.Y,kifu.Size))
			}
			fmt.Println("落子")
			if n.GetColor()!=""{
				gtp.Move(n.GetColor(),goban.CoorToBoardNode(n.X,n.Y,kifu.Size))
			}
			return false
		})
		result,err:=gtp.GenMove("B")
		if err!=nil{
			panic(err)
		}
		fmt.Println(result)
		return
	}
	commands := strings.Fields(afters)
	for g := 1; g <= game; g++ {
		fmt.Println("Before Game Start:", runtime.NumGoroutine())
		client, err := gtpcommand.NewCMDClientString(shell)
		if err != nil {
			panic(err)
		}
		gtp := gtpengine.NewGTPCommand(client)
		gtp.ShowLog(true)
		for _, v := range commands {
			_, _ = gtp.SendCMD(v)
		}
		color := "B"
		_, _ = gtp.ClearBoard()
		for i := 1; i <= move; i++ {

			fmt.Println("Move before:", runtime.NumGoroutine(), "，当前开始对局数为：", g)
			result, err := gtp.GenMove(color)
			if err != nil {
				panic(err)
			}
			fmt.Println(result.Result)
			if gtp.Version() >= 0.17 {
				outputs, _ := goban.ParseLZOutputV17(result.ErrOut, 19, 3)
				if len(outputs) == 0 {
					fmt.Printf("%v\n", result)
					panic("分支为空")
				} else {
					fmt.Println("分支数量为：", len(outputs))
				}
			} else {
				outputs, _ := goban.ParseLZOutput(result.ErrOut, 19, 3)
				if len(outputs) == 0 {
					fmt.Printf("%v\n", result)
					panic("分支为空")
				} else {
					fmt.Println("分支数量为：", len(outputs))
				}
			}
			if color == "B" {
				color = "W"
			} else {
				color = "B"
			}
			fmt.Println("Move after:", runtime.NumGoroutine())
		}
		client.Close()
		fmt.Println("After Game End:", runtime.NumGoroutine())
	}

}
